package com.example.rpcdemo.core.server;

import com.example.rpcdemo.core.protocol.RpcRequest;
import com.example.rpcdemo.core.protocol.RpcResponse;
import com.example.rpcdemo.core.codec.RpcDecoder;
import com.example.rpcdemo.core.codec.RpcEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class RpcServer {
    private final int port;
    private final RpcServerHandler handler = new RpcServerHandler();
    private ChannelFuture channelFuture;
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    
    public RpcServer(int port) {
        this.port = port;
    }
    
    public void addService(String serviceName, Object service) {
        handler.addService(serviceName, service);
    }
    
    public void addService(String serviceName, String interfaceName, Object service) {
        handler.addService(serviceName, service);
    }
    
    public int getPort() {
        return port;
    }
    
    public void start() throws Exception {
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new RpcDecoder(RpcRequest.class))
                                .addLast(new RpcEncoder())
                                .addLast(handler);
                    }
                })
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true);
        
        channelFuture = bootstrap.bind(port).sync();
        System.out.println("RPC Server started on port " + port);
    }
    
    public void stop() {
        if (channelFuture != null) {
            channelFuture.channel().close();
        }
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
        }
        System.out.println("RPC Server stopped");
    }
}